package com.example.gitpart03;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.gitpart03.Book;
import com.example.gitpart03.ChapterParser;

import java.util.ArrayList;
import java.util.List;

public class BookReaderActivity extends AppCompatActivity {

    public static final String EXTRA_BOOK = "book";
    public static final String EXTRA_CHAPTER = "chapter";

    private Book book;
    private int currentChapterIndex = 0;
    private List<String> chapterContents = new ArrayList<>();

    private TextView tvChapterTitle;
    private TextView tvChapterContent;
    private Button btnPrevChapter;
    private Button btnNextChapter;

    // 阅读设置相关
    private boolean isNightMode = false;
    private float textSizeScale = 1.0f;
    private SeekBar sbTextSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_reader);

        initViews();
        initData();
        updateChapterDisplay();
        setupSettings();
    }

    private void initViews() {
        tvChapterTitle = findViewById(R.id.tvChapterTitle);
        tvChapterContent = findViewById(R.id.tvChapterContent);
        btnPrevChapter = findViewById(R.id.btnPrevChapter);
        btnNextChapter = findViewById(R.id.btnNextChapter);
        sbTextSize = findViewById(R.id.sbTextSize);

        btnPrevChapter.setOnClickListener(v -> switchChapter(false));
        btnNextChapter.setOnClickListener(v -> switchChapter(true));
    }

    private void initData() {
        book = getIntent().getParcelableExtra(EXTRA_BOOK);
        int startChapter = getIntent().getIntExtra(EXTRA_CHAPTER, 1);

        // 模拟从 ChapterParser 解析章节内容（这里可替换为真实文件/网络加载）
        String sampleBookContent = "第1章 序章\n" +
                "这是小说第1章的精彩内容...\n\n" +
                "第2章 冒险开始\n" +
                "主角踏上了新的旅程...\n\n" +
                "第3章 神秘相遇\n" +
                "遇到了改变命运的人...";
        chapterContents = ChapterParser.parseChapters(sampleBookContent);

        // 找到起始章节索引（简单处理，假设章节标题是“第X章” 格式）
        if (!chapterContents.isEmpty()) {
            for (int i = 0; i < chapterContents.size(); i++) {
                if (chapterContents.get(i).startsWith("第" + startChapter + "章")) {
                    currentChapterIndex = i;
                    break;
                }
            }
        }
    }

    private void updateChapterDisplay() {
        if (chapterContents.isEmpty() || currentChapterIndex < 0 || currentChapterIndex >= chapterContents.size()) {
            Toast.makeText(this, "无效章节", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        String chapterText = chapterContents.get(currentChapterIndex);
        // 拆分标题和内容（简单按第一行分割）
        String[] parts = chapterText.split("\n", 2);
        String chapterTitle = parts[0];
        String chapterContent = parts.length > 1 ? parts[1] : "";

        tvChapterTitle.setText(chapterTitle);
        tvChapterContent.setText(chapterContent);
        // 应用阅读设置
        applyReadingSettings();
    }

    private void switchChapter(boolean isNext) {
        if (isNext) {
            currentChapterIndex++;
            if (currentChapterIndex >= chapterContents.size()) {
                currentChapterIndex = chapterContents.size() - 1;
                Toast.makeText(this, "已到最后一章", Toast.LENGTH_SHORT).show();
            }
        } else {
            currentChapterIndex--;
            if (currentChapterIndex < 0) {
                currentChapterIndex = 0;
                Toast.makeText(this, "已到第一章", Toast.LENGTH_SHORT).show();
            }
        }
        updateChapterDisplay();
    }

    // 阅读设置相关逻辑
    private void setupSettings() {
        // 字体大小调节
        sbTextSize.setProgress((int) ((textSizeScale - 0.5f) * 10));
        sbTextSize.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textSizeScale = 0.5f + progress * 0.1f;
                applyTextSize();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void applyReadingSettings() {
        applyNightMode();
        applyTextSize();
    }

    private void applyNightMode() {
        if (isNightMode) {
            getWindow().getDecorView().setBackgroundColor(getResources().getColor(android.R.color.black));
            tvChapterTitle.setTextColor(getResources().getColor(android.R.color.white));
            tvChapterContent.setTextColor(getResources().getColor(android.R.color.white));
        } else {
            getWindow().getDecorView().setBackgroundColor(getResources().getColor(android.R.color.white));
            tvChapterTitle.setTextColor(getResources().getColor(android.R.color.black));
            tvChapterContent.setTextColor(getResources().getColor(android.R.color.black));
        }
    }

    private void applyTextSize() {
        tvChapterTitle.setTextSize(20 * textSizeScale);
        tvChapterContent.setTextSize(16 * textSizeScale);
    }

    // 菜单（可扩展更多设置）
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.reader_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_night_mode) {
            isNightMode = !isNightMode;
            applyNightMode();
            item.setTitle(isNightMode ? "日间模式" : "夜间模式");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}